package com.discuss.community.service.impl;

import com.discuss.community.service.DataService;
import com.discuss.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DataServiceImpl implements DataService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    private final SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
    
    
    @Override
    public void recordUV(String ip) {
        String uvKey = RedisKeyUtil.getUVKey(format.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(uvKey, ip);
    }

    @Override
    public long calculateUV(Date start, Date end) {
        if(start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        // 整理日期范围内的 key
        List<String> keys = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while(!calendar.getTime().after(end)) {
            String uvKey = RedisKeyUtil.getUVKey(format.format(calendar.getTime()));
            keys.add(uvKey);
            calendar.add(Calendar.DATE, 1);
        }

        // 合并这些数据
        String uvKey = RedisKeyUtil.getUVKey(format.format(start), format.format(end));
        
        redisTemplate.opsForHyperLogLog().union(uvKey, keys.toArray(new String[0]));

        return redisTemplate.opsForHyperLogLog().size(uvKey);
    }

    // 将指定用户计入DAU
    @Override
    public void recordDAU(int userId) {
        String dauKey = RedisKeyUtil.getDAUKey(format.format(new Date()));
        
        redisTemplate.opsForValue().setBit(dauKey, userId, true);
    }

    // 统计指定范围内的DAU
    @Override
    public long calculateDAU(Date start, Date end) {
        if(start == null || end == null) {
            throw new IllegalArgumentException("参数不能为空");
        }

        List<byte[]> keys = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        
        calendar.setTime(start);
        
        while(!calendar.getTime().after(end)) {
            String dauKey = RedisKeyUtil.getDAUKey(format.format(calendar));
            keys.add(dauKey.getBytes(StandardCharsets.UTF_8));
            calendar.add(Calendar.DATE, 1);
        }
        
        return redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                String dauKey = RedisKeyUtil.getDAUKey(format.format(start), format.format(end));
                connection.bitOp(RedisStringCommands.BitOperation.OR,
                        dauKey.getBytes(StandardCharsets.UTF_8), keys.toArray(new byte[0][0]));
                return connection.bitCount(dauKey.getBytes(StandardCharsets.UTF_8));
            }
        });

    }


}
